import 'dart:math';

import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nfmovies/model/nf_home_info_model.dart';
import 'package:flutter_nfmovies/net/dio_util.dart';
import 'package:flutter_nfmovies/page/nf_home_item_widget.dart';
import 'package:flutter_nfmovies/util/cache_util.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart';

class NFNewMoviePage extends StatefulWidget {
  @override
  _NFNewMoviePageState createState() => _NFNewMoviePageState();
}

class _NFNewMoviePageState extends State<NFNewMoviePage>
    with AutomaticKeepAliveClientMixin {
  final String _nfUrl = 'https://www.nfmovies.com/';

  List<NfHomeInfoModel> nfHomes = [];

  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    _initData();

    super.initState();
  }

  _initData() {
    DioUtil.instance.get(
        _nfUrl,
        (String data) => setState(() {
              nfHomes = [];
              parse(data)
                  .body
                  .getElementsByClassName('myui-panel-box clearfix')
                  .forEach((element) {
                var nfHomeInfoModel = NfHomeInfoModel();
                List<NfHomeItemInfoModel> items = [];
                element
                    .querySelector('ul.myui-vodlist.clearfix')
                    ?.querySelectorAll('li')
                    ?.forEach((item) {
                  var nfHomeItemInfoModel = NfHomeItemInfoModel();
                  dom.Element videoBox =
                      item.getElementsByClassName('myui-vodlist__box')?.first;
                  dom.Element videoBoxDetail = item
                      .getElementsByClassName('myui-vodlist__detail')
                      ?.first;
                  var videoBoxA = videoBox.querySelector('a');
                  var videoBoxTop = videoBox
                      ?.getElementsByClassName('pic-tag pic-tag-top')
                      ?.first;
                  var videoBoxText = videoBox
                      ?.getElementsByClassName('pic-text text-right')
                      ?.first;
                  nfHomeItemInfoModel
                    ..title = videoBoxA?.attributes['title']
                    ..subTitle = videoBoxText?.text
                    ..img = '$_nfUrl${videoBoxA?.attributes['data-original']}'
                    ..url = '$_nfUrl${videoBoxA?.attributes['href']}'
                    ..score = videoBoxTop?.text
                    ..starring = videoBoxDetail?.querySelector('p')?.text;

                  items.add(nfHomeItemInfoModel);
                });
                var title =
                    element?.querySelector('.myui-panel_hd h3')?.text?.trim() ??
                        '';
                var element2 = element?.querySelector('.myui-panel_hd a');
                var subTitle = element2?.text?.trim() ?? '';
                if (!TextUtil.isEmpty(title) &&
                    !TextUtil.isEmpty(title) &&
                    items.isNotEmpty) {
                  var attribute = element2?.attributes;
                  var subUrl;
                  if (null != attribute) {
                    subUrl = attribute['href'];
                  }
                  nfHomeInfoModel
                    ..title = '$title'
                    ..subTitle = '$subTitle'
                    ..subUrl = subUrl
                    ..data = items;
                  nfHomes.add(nfHomeInfoModel);
                }
              });
            }),
        (code, message) => null);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    var data;
    var nextInt2 = 0;
    if (nfHomes.isNotEmpty) {
      var nextInt = Random().nextInt(nfHomes.isEmpty ? 1 : nfHomes.length);
      data = nfHomes[nextInt]?.data;
      nextInt2 =
          Random().nextInt((data != null && data.isNotEmpty) ? data.length : 1);
    }
    return Container(
      child: Stack(
        children: [
          nfHomes.isNotEmpty
              ? CacheUtil.cacheImage(
                  data[nextInt2].img,
                  fit: BoxFit.fitHeight,
                  height: double.infinity,
                  width: double.infinity,
                )
              : SizedBox(),
          Container(
            color: Colors.black38,
          ),
          SingleChildScrollView(
            controller: _scrollController,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                AppBar(
                  title: Text('奈菲'),
                ),
                nfHomes.isNotEmpty
                    ? Flexible(
                        fit: FlexFit.loose,
                        child: ListView.separated(
                            controller: _scrollController,
                            shrinkWrap: true,
                            itemBuilder: (_, index) {
                              var nfHome = nfHomes[index];
                              return NfHomeItemWidget(
                                data: nfHome,
                              );
                            },
                            separatorBuilder: (_, index) => SizedBox(
                                  height: 8.h,
                                ),
                            itemCount: nfHomes.length))
                    : Center(
                        child: ElevatedButton(
                            onPressed: () => _initData(), child: Text('刷新')),
                      )
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
